package web.servlet;

import domain.Account;
import domain.Product;
import service.CatalogService;
import service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductsServlet extends HttpServlet {
    private static final String SEARCH = "/WEB-INF/jsp/catalog/searchProducts.jsp";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("SearchProductsServlet...");
        String KEYWORDS = request.getParameter("keyword");
        CatalogService catalogService = new CatalogService();
        List<Product> productList = catalogService.searchProductList(KEYWORDS);
        HttpSession session = request.getSession();
        session.setAttribute("productList", productList);


        System.out.println(productList);
        Account account = (Account) session.getAttribute("account");

        if (account != null) {
            String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath() + request.getServletPath() + "?" + (request.getQueryString());

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + " 查找商品" + "  " + productList;
            logService.insertLogInfo(account.getUsername(), logInfo);

        }
        request.getRequestDispatcher(SEARCH).forward(request, response);
        //       System.out.println(SEARCH);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
